<template>
   <div  class="bunker-content">
          <el-form   ref="portFormRef"  :model="props.portFormObj">
          <el-table :data="props.portFormObj.recordData" stripe :border="true"  :span-method="arraySpanMethod" >
            <el-table-column prop="name" label="" width="90">
            </el-table-column>
            <el-table-column prop="VLSFO" header-align="center" width="">
              <template #header>
                <div style="display: flex;justify-content: space-around;">
                  <span>VLSFO(MT)</span>
                  <span>PRICE(USD/MT)</span>
                </div>          
            </template>
              <template #default="scope">
                <div style="display: flex;justify-content: space-around;" v-if="scope.$index!=3&&scope.$index!=4">
                  <el-form-item :prop="'recordData.' + scope.$index + '.VLSFO'" style="width: 90px;">
                  <el-input-number v-model="scope.row.VLSFO" :precision="3" :step="0.1" :max="10000" :controls="false"
                    placeholder="VLSFO" />
                  </el-form-item>
                  <el-form-item :prop="'recordData.' + scope.$index + '.VLSFOPRICE'"  style="width: 90px;">
                    <el-input-number v-model="scope.row.VLSFOPRICE" :precision="3" :step="0.1" :max="10000" :controls="false"
                      placeholder="" />
                  </el-form-item>
                </div>
                <div v-else-if="scope.$index==3" class="brunk-upload" style="display: flex;align-items: center;"> 
                  <span>BND</span>
                  <el-form-item style="width: 90%;"> 
                  <DragUpload
                  :limit="10"
                  accept=".pdf,.docx,.xlsx,.doc,.docx,.txt,.zip,.rar,.jpg,.png,.jpeg"
                  @upload-start="handleUploadStart($event,'bdn',scope.$index)"
                  @files-change="handleFilesChange($event,'bdn',scope.$index)"
                  @file-removed="handleFileRemoved($event,'bdn',scope.$index)"
                  v-model="portFormObj.recordData[2].BDN"
                  :placeholderText="placeholderText"
                  />
                </el-form-item>
                </div>
                
               
              </template>
            </el-table-column>
             <!-- <el-table-column prop="PRICE" label="PRICE" header-align="center" width="105">
              <template #default="scope">
                <el-form-item :prop="'recordData.' + scope.$index + '.VLSFOPRICE'" >
                  <el-input-number v-model="scope.row.VLSFOPRICE" :precision="2" :step="0.1" :max="10000" :controls="false"
                    placeholder="PRICE" />
                </el-form-item>
              </template>
            </el-table-column> -->
            <el-table-column prop="LSMGO" label="LSMGO" header-align="center" width="">
              <template #header>
                <div style="display: flex;justify-content: space-around;">
                  <span>LSMGO(MT)</span>
                  <span>PRICE(USD/MT)</span>
                </div>          
            </template>
              <template #default="scope">
                <div style="display: flex;justify-content: space-around;" v-if="scope.$index!=3&&scope.$index!=4">
                  <el-form-item :prop="'recordData.' + scope.$index + '.LSMGO'" style="width: 90px;">
                  <el-input-number v-model="scope.row.LSMGO" :precision="3" :step="0.1" :max="10000" :controls="false"
                    placeholder="LSMGO" />
                  </el-form-item>
                  <el-form-item :prop="'recordData.' + scope.$index + '.LSMGOPRICE'"  style="width: 90px;">
                    <el-input-number  v-model="scope.row.LSMGOPRICE" :precision="3" :step="0.1" :max="10000" :controls="false"
                      placeholder="" />
                  </el-form-item>
                </div>
                <div v-else-if="scope.$index==3" class="brunk-upload">
                  <span>INVOICE</span>
                  <el-form-item style="width: 90%;"> 
                  <DragUpload
                  :limit="10"
                  accept=".pdf,.docx,.xlsx,.doc,.docx,.txt,.zip,.rar,.jpg,.png,.jpeg"
                  @upload-start="handleUploadStart($event,'invoiceFile',scope.$index)"
                  @files-change="handleFilesChange($event,'invoiceFile',scope.$index)"
                  @file-removed="handleFileRemoved($event,'invoiceFile',scope.$index)"
                   v-model="portFormObj.recordData[2].INVOICE"
                   :placeholderText="placeholderText"
                  />
                </el-form-item>
                </div>
                <div v-if="scope.$index==4" class="brunk-upload">
                  <span style="width:100px">DATE ISSUE </span>
                  <el-form-item >
                    <el-date-picker style="width: 90px;" type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD" placeholder="" v-model="portFormObj.recordData[2].DATEISSUE" />
                  </el-form-item>
                  <span style="width:100px">&nbsp;&nbsp;&nbsp;&nbsp;DUE DATE</span>
                  <el-form-item >
                    <el-date-picker style="width: 90px;" type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD" placeholder="" v-model="portFormObj.recordData[2].DUEDATE" />
                  </el-form-item>
                </div> 
              </template>
            </el-table-column>
            <el-table-column prop="LNG" label="LNG" header-align="center" width="420">
              <template #header>
                <div style="display: flex;justify-content: space-around;">
                  <span>LNG(MMBTU)</span>
                  <span>PRICE(USD/MMBTU)</span>
                  <span>LNG(MT)</span>
                </div>          
            </template>
              <template #default="scope">
                <div style="display: flex;justify-content: space-around;" v-if="scope.$index!=3&&scope.$index!=4">
                  <el-form-item :prop="'recordData.' + scope.$index + '.LNG'" style="width: 120px;">
                  <el-input-number v-model="scope.row.LNG" :precision="3" :step="0.1" :max="100000" :controls="false"
                    placeholder="LSMGO" />
                </el-form-item>
                <el-form-item :prop="'recordData.' + scope.$index + '.LNGPRICE'"  style="width: 120px;">
                  <el-input-number v-model="scope.row.LNGPRICE"  :precision="3" :step="0.1" :max="100000" :controls="false" />
                </el-form-item>
                  <el-form-item :prop="'recordData.' + scope.$index + '.LNGMT'"  style="width: 100px;">
                  <el-input-number v-model="scope.row.LNGMT"  :precision="3" :step="0.1" :max="100000" :controls="false" />
                </el-form-item>
                </div>
                <div v-else-if="scope.$index==3" class="brunk-upload">
                  <span>BANK SLIP</span>
                  <el-form-item style="width: 90%;"> 
                  <DragUpload
                  :limit="1"
                  accept=".pdf,.docx,.xlsx,.doc,.docx,.txt,.zip,.rar,.jpg,.png,.jpeg"
                  @upload-start="handleUploadStart($event,'bankSlipFile',scope.$index)"
                  @files-change="handleFilesChange($event,'bankSlipFile',scope.$index)"
                  @file-removed="handleFileRemoved($event,'bankSlipFile',scope.$index)"
                   v-model="portFormObj.recordData[2].BANKSLIP"
                   :placeholderText="placeholderText"
                  />
                </el-form-item>
                </div>
                <div v-if="scope.$index==4" class="brunk-upload">
                  <span>DATE PAID</span>
                  <el-form-item >
                    <el-date-picker style="width: 160px;" type="date" format="YYYY/MM/DD" value-format="YYYY-MM-DD" placeholder="" v-model="portFormObj.recordData[2].DATEPAID" />
                  </el-form-item>
                </div> 
              </template>
            </el-table-column>
            <el-table-column prop="OTHERFEE" label="OTHER FEE" header-align="center" width="120">
               <template #header>
                <div style="display: flex;justify-content: center;">
                  <span style="line-height: 12px;">OTHER FEE</span>
                </div>          
              </template>
              <template #default="scope">
                  <el-form-item :prop="'recordData.' + scope.$index + '.OTHERFEE'" style="" v-if="scope.$index < 3">
                  <el-input-number v-model="scope.row.OTHERFEE" :precision="3" :step="0.1" :max="100000" :controls="false"/>
                </el-form-item>              
              </template>
            </el-table-column>
            <el-table-column prop="AMOUNT" label="AMOUNT" header-align="center"  width="120">
              <template #default="scope">
                <el-form-item v-if="scope.$index==0">
                  <el-input readonly :value="robArrAmount" placeholder="" :precision="3" :step="0.1" />
                </el-form-item>
                <el-form-item v-if="scope.$index==1">
                  <el-input readonly :value="robDepAmount" placeholder="" :precision="3" :step="0.1" />
                </el-form-item>
                <el-form-item v-if="scope.$index==2">
                  <el-input readonly :value="suppliedAmount" placeholder="" :precision="2" :step="0.1" />
                </el-form-item> 
              </template>
            </el-table-column>
            <el-table-column prop="DATETIME" label="DATE/TIME" header-align="center" width="180">
              <template #default="scope">
                <el-form-item :prop="'recordData.' + scope.$index + '.DATETIME'" v-if="scope.$index!=3&&scope.$index!=4">
                  <el-date-picker  type="datetime" v-model="scope.row.DATETIME" format="YYYY/MM/DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"   />
                </el-form-item> 
              </template>
            </el-table-column> 
          </el-table>
        </el-form>
        <div class="pane-footer">
          <el-button @click="cancelHandle">{{ $t("ship.button.cancel") }}</el-button>
          <el-button type="primary" @click="submitDialogPort">{{ $t("ship.button.submit") }}</el-button>
        </div>
      </div>  

</template>

<script lang="ts" setup>
// @ts-nocheck
import { ref, onMounted,onUnmounted, computed, reactive, nextTick, defineEmits, watch } from "vue";
import service from "@/utils/request";
import { convertUrl } from "@/utils/tencentCos";
import { ElNotification, ElMessageBox, ElMessage } from "element-plus";
import DragUpload from '@/components/FormDataIUpload/index.vue'; 
import { id } from "element-plus/es/locales.mjs";
const placeholderText=" Upload File "

const emit = defineEmits(["saveOk",'getDetail']);

const proxy = getCurrentInstance()?.proxy;
const props = defineProps({
  data: {
    type: Object,
    default: () => { }
  },
  rowData: {
    type: Object,
    default: () => { }
  },
  portFormObj: {
    type: Object,
    default: () => { }
  },
  portRotationId: {
    type: Number,
    default: 0
  },
  titleValue: {
    type: String,
    default: ""
  }
});



const portFormRef = ref()
const submitDialogPort = () => {
    portFormRef.value.validate(async (valid) => {
      if (!valid) {
        // @ts-ignore
        ElNotification.warning({
          title: "Prompt information", 
          message: "verification not success！",
          position: "bottom-right",
        });
        return;
      }
      const params = props.portFormObj.recordData.map((item, index) => {
        const { VLSFO,VLSFOPRICE, LSMGO,LSMGOPRICE, LNG,LNGPRICE,LNGMT,OTHERFEE, DATETIME, BDN,INVOICE ,DATEISSUE,DATEPAID,BANKSLIP,DUEDATE } = item


        if (index === 0) {
          return { robArrVlsfo: VLSFO,robArrVlsfoPrice:VLSFOPRICE, robArrLsmgo: LSMGO,robArrOtherFee:OTHERFEE,robArrLsmgoPrice: LSMGOPRICE, robArrLng: LNG,  robArrLngPrice: LNGPRICE,robArrLngMt:LNGMT,robArrDate: DATETIME, robArrBdnFile: null,robArrInvoiceFile: INVOICE?INVOICE:null, robArrDateIssue: DATEISSUE, robArrDatePaid: DATEPAID, robArrBankSlipFile: BANKSLIP?BANKSLIP:null }
        } else if (index === 1) {
          return { robDepVlsfo: VLSFO,robDepVlsfoPrice:VLSFOPRICE, robDepLsmgo: LSMGO,robDepOtherFee:OTHERFEE, robDepLsmgoPrice: LSMGOPRICE, robDepLng: LNG,  robDepLngPrice: LNGPRICE, robDepLngMt:LNGMT,robDepDate: DATETIME,robDepBdnFile: null, robDepInvoiceFile: INVOICE?INVOICE:null,robDepDateIssue: DATEISSUE, robDepDatePaid: DATEPAID, robDepBankSlipFile: BANKSLIP?BANKSLIP:null  }
        } else if (index === 2) {
          return { suppliedVlsfo: VLSFO,suppliedVlsfoPrice:VLSFOPRICE, suppliedLsmgo: LSMGO, suppliedOtherFee:OTHERFEE, suppliedLsmgoPrice: LSMGOPRICE, suppliedLng: LNG,  suppliedLngPrice: LNGPRICE, suppliedLngMt:LNGMT, suppliedDate: DATETIME, suppliedBdnFile: BDN?BDN:null,suppliedInvoiceFile: INVOICE?INVOICE:null,suppliedDateIssue: DATEISSUE, suppliedDatePaid: DATEPAID, suppliedBankSlipFile: BANKSLIP?BANKSLIP:null,dueDate:DUEDATE  }

        }
      })
      const info =  props.rowData.details.find(item => { return item.portName == props.titleValue.value })
      console.log(props.portFormObj)
      const formData = Object.assign({ portRotationId: props.portFormObj.id }, ...params)
      console.log('formData',formData)
      if(formData.suppliedBdnFile.length>0){
        let c=[]
        let d=[]
      	formData.suppliedBdnFile.forEach((item,index)=>{
          if(item.url){
          	c.push(item.url)
          }else{
            d.push(item)
          }
      	})
        formData.suppliedBdnFile=d
        formData.suppliedBdn=c.join('&&&')
      }
      if(formData.suppliedInvoiceFile.length>0){
        let c=[]
        let d=[]
      	formData.suppliedInvoiceFile.forEach((item,index)=>{
          if(item.url){
          	c.push(item.url)
          }else{
            d.push(item)
          }
      	})
        formData.suppliedInvoiceFile=d
        formData.suppliedInvoice=c.join('&&&')
      }
      if(formData.suppliedBankSlipFile.length>0){
        let c=[]
        let d=[]
      	formData.suppliedBankSlipFile.forEach((item,index)=>{
          if(item.url){
          	c.push(item.url)
          }else{
            d.push(item)
          }
      	})
        formData.suppliedBankSlipFile=d
        formData.suppliedBankSlip=c.join('&&&')
      }
      const formDataInfo = new FormData()
      for (const [k, n] of Object.entries(formData)) {
        if (Array.isArray(n)) { 
        for (let i = 0; i < n.length; i++) {
          formDataInfo.append(k, n[i]);
        }
      }else if(n){
          formDataInfo.append(k, n);
      }
    }
      let result = await service.post("/shipping/schedule/updatePortBunkerData", formDataInfo);
      // @ts-ignore
      ElNotification.success({
        title: "Prompt information",
        message: "Update the data success!",
        position: "bottom-right",
      });
      emit("saveOk");
    });
  }

const cancelHandle = () => {
  emit("saveOk");
};


const handleUploadStart=(files,type,index)=> {
}

const handleFilesChange=(files,type,index)=> {
 if(files.length>0){
  if(type=='bdn'){
    props.portFormObj.recordData[2].BDN.push(files[files.length-1].file)
  }
  if(type=='invoiceFile'){
    props.portFormObj.recordData[2].INVOICE.push(files[files.length-1].file)
  }
  if(type=='bankSlipFile'){
    props.portFormObj.recordData[2].BANKSLIP = [files[0].file]
  }
  }
}




const handleFileRemoved=(file,type,index)=> {
  if(type=='invoiceFile'){
    let index2=props.portFormObj.recordData[2].INVOICE.findIndex(item=>item.name==file.name&&item.url==file.url)
    console.log('[ index2 ] >', index2)
    if(index2==-1){
      return;
    }
   props.portFormObj.recordData[2].INVOICE.splice(index2,1)
  }else if(type=='bankSlipFile'){
    
    props.portFormObj.recordData[2].BANKSLIP = []
  }else if(type=='bdn'){
    let index2=props.portFormObj.recordData[2].BDN.findIndex(item=>item.name==file.name&&item.url==file.url)
    if(index2==-1){
      return;
    }
    props.portFormObj.recordData[2].BDN.splice(index2,1)
  }

}
const arraySpanMethod = (
  {row,
  column,
  rowIndex,
  columnIndex,}
) => { 
  // if (rowIndex  === 3) {
  //   if (columnIndex === 4) {
  //     return [1, 2]
  //   }
  // }
  if (columnIndex  === 0) {
    if (rowIndex === 2) {
     return {
        rowspan: 3,
        colspan: 1,
      }
    }else if (rowIndex === 3||rowIndex==4) {
      return {
        rowspan: 0,
        colspan: 0,
      }

    }else{
      return {
        rowspan: 1,
        colspan: 1,
      }
    }

  }else
    if (rowIndex === 3||rowIndex==4) {
      return {
        rowspan: 1,
        colspan: 2,
      }
    }
}


/**
 * 总计计算
 * VLSFO*PRICE+LSMGO*PRICE+LNG*PRICE+OTHERFEE=AMOUNT

**/ 
  const robArrAmount=computed(()=>{
    let total = 0;
    
    const { LNGPRICE,LSMGOPRICE,VLSFOPRICE, VLSFO, LSMGO, LNG,OTHERFEE } =  props.portFormObj.recordData[0] || {};
    total= (VLSFO || 0) * (VLSFOPRICE || 0) + (LSMGO || 0) * (LSMGOPRICE || 0) + (LNG || 0) * (LNGPRICE || 0)+ (OTHERFEE || 0) ;
    return total.toFixed(3);;
  })
  const suppliedAmount=computed(()=>{
    let total = 0;
    const { LNGPRICE,LSMGOPRICE,VLSFOPRICE, VLSFO, LSMGO, LNG,OTHERFEE } =  props.portFormObj.recordData[2] || {};
    total= (VLSFO || 0) * (VLSFOPRICE || 0) + (LSMGO || 0) * (LSMGOPRICE || 0) + (LNG || 0) * (LNGPRICE || 0)+ (OTHERFEE || 0) ;
    return total.toFixed(2);
  })
  const  robDepAmount=computed(()=>{
    let total = 0;
    const { LNGPRICE,LSMGOPRICE,VLSFOPRICE, VLSFO, LSMGO, LNG,OTHERFEE } =  props.portFormObj.recordData[1] || {};
    total= (VLSFO || 0) * (VLSFOPRICE || 0) + (LSMGO || 0) * (LSMGOPRICE || 0) + (LNG || 0) * (LNGPRICE || 0)+ (OTHERFEE || 0) ;
    return total.toFixed(3);
  })
</script>

<style scoped lang="scss">
  .el-table .cell {
    text-align: center !important;
    color: #888 !important;
    white-space: nowrap!important;
  }
  .el-table__expand-column .cell {
    display: none;
  }
.detail-table-add{
  ::v-deep.el-table td.el-table__cell div {
    overflow: visible !important;
  }
  ::v-deep .el-form-item__error{
    line-height:0.5 !important;
  }
  ::v-deep .el-input__inner {
    height: 28px !important;
  }
  ::v-deep .el-form-item__content{
    height: 28px !important;
    .el-input__wrapper{
      height: 28px!important;
    }
  }
}
  .header-wrapper {
    border: 1px solid #ebeef5;
    border-bottom: none;
    padding: 10px;
  }

  .daf-table {
    margin: 0;
    padding: 0;
  }

  .tips {
    text-align: right;
    margin: 6px 0;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    .el-button {
      margin-right: 14px;
      // width: 6px !important;
      // height: 6px;
    }
  }

  .el-icon-arrow-right {
    margin-right: 10px;
    margin-left: 10px;
    cursor: pointer;
  }

  .pane-footer {
    margin-top: 20px;
    text-align: right;
  } 
 
  .schedule .el-form-item {
    margin-bottom: 3px !important;
  }
 
  ::v-deep .el-form-item{
    margin-bottom: 3px !important;
  }

  .schedule{
    position: relative;
     
  }
  .el-table .cell{
     padding: 0 12px !important;
  }
  ::v-deep .bunker-content .el-input__prefix{
    display: none!important;
  }
  ::v-deep .bunker-content .el-input-number.is-without-controls .el-input__wrapper{
    padding: 0 12px !important;
  }

  ::v-deep .bunker-content .el-table .cell{
     padding: 0 12px !important;
  }
  .header_title{
    font-size: 12px;
    font-weight: 600; 
    position: absolute;
    top: 32px;
    right: 20px;
  }
  my-custom-dropdown .el-select-dropdown__item {
  display: inline-block; /* 或者其他布局方式 */
  margin-right: 10px; /* 根据需要调整间距 */
}
.brunk-upload{
  display: flex;
  align-items: center;
  >span{
    display: inline-block;
    text-align: left;
    width: 71px;
  }
}
</style>